% This script imputs missing values in a data matrix 'M' by sampling from
% non-missing values in the same row or column with or without replacement
% Date: 2019-1-27
function f = imputeNaN(M,dim,repInd)
% M: n-by-k data matrix
% dim: indicates imputation by row or column, '1' for row & '2' for column
% repInd = '1' if imputed values are drawn with replacement from the
% non-missing values in the same column; = '0' if drawn without replacement
for i = 1:size(M,dim) % loop in columns
    switch dim,
        case 2, % impute column by column
            Mi = M(:,i);  
            nonMSi = Mi(~isnan(Mi));  % collect non-missing values in the column
            mInd   = find(isnan(Mi)); % find index of missing values
            M(mInd,i) = randsample(nonMSi,length(mInd),repInd); % impute missing values
        case 1, % impute row by row
            Mi = M(i,:);  
            nonMSi = Mi(~isnan(Mi));  % collect non-missing values in the column
            mInd   = find(isnan(Mi)); % find index of missing values
            M(i,mInd) = randsample(nonMSi,length(mInd),repInd); % impute missing values
    end;
end
f = M;